package com.ruoyi.serve.service.impl;

import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SshUtils;
import com.ruoyi.common.utils.ping.RemotePortScannerSSH;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.ruoyi.serve.mapper.ServerInfoMapper;
import com.ruoyi.serve.domain.ServerInfo;
import com.ruoyi.serve.service.IServerInfoService;

/**
 * 服务列表Service业务层处理
 * 
 * @author liu
 * @date 2023-11-09
 */
@Service
public class ServerInfoServiceImpl implements IServerInfoService 
{
    @Autowired
    private ServerInfoMapper serverInfoMapper;

    long checkInterval = 5 * 60 * 1000;

    /**
     * 查询服务列表
     * 
     * @param serverId 服务列表主键
     * @return 服务列表
     */
    @Override
    public ServerInfo selectServerInfoByServerId(Long serverId)
    {
        return serverInfoMapper.selectServerInfoByServerId(serverId);
    }

    /**
     * 查询服务列表列表
     * 
     * @param serverInfo 服务列表
     * @return 服务列表
     */
    @Override
    public List<ServerInfo> selectServerInfoList(ServerInfo serverInfo)
    {
        List<ServerInfo> serverInfos = serverInfoMapper.selectServerInfoList(serverInfo);
        for (ServerInfo server : serverInfos){
            String serverAddress = server.getHostIp();

            int isServerHealthy = isServerHealthy(serverAddress);
            server.setIsPing(isServerHealthy);
            System.out.println(serverAddress + " is healthy: " + isServerHealthy);

            this.updateServerInfo(server);
        }
        return serverInfos;
    }

//    @Scheduled(cron="0 0/1 *  * * ? ")
    public void updateServeInfo(){
        System.out.println("==================开始更新所有服务状态=====================");
        List<ServerInfo> list = serverInfoMapper.selectServerInfoList(null);

        for (ServerInfo serve : list) {
            List<String> execCmd = SshUtils.execCmd(serve.getHostIp(), serve.getUserName(),
                    serve.getPassword(), Integer.parseInt(serve.getSshPort()));

            if (execCmd.size() == 3){
                try {
                    serve.setCpuOccupy(String.valueOf(100 - Float.parseFloat(execCmd.get(1))));
                }catch (Exception e){
                    System.out.println("cpu获取异常: " + execCmd.get(1) );
                }

                serve.setUseMemory(execCmd.get(0).split(",")[1]);
                serve.setTotalMemory(execCmd.get(0).split(",")[0]);
                serve.setTotalDisk(execCmd.get(2).split(",")[0]);
                serve.setUseDisk(execCmd.get(2).split(",")[1]);

                this.updateServerInfo(serve);
            }
        }

    }

    /**
     * 新增服务列表
     * 
     * @param serverInfo 服务列表
     * @return 结果
     */
    @Override
    public int insertServerInfo(ServerInfo serverInfo)
    {
        serverInfo.setCreateTime(DateUtils.getNowDate());
        return serverInfoMapper.insertServerInfo(serverInfo);
    }

    /**
     * 修改服务列表
     * 
     * @param serverInfo 服务列表
     * @return 结果
     */
    @Override
    public int updateServerInfo(ServerInfo serverInfo)
    {
        serverInfo.setUpdateTime(DateUtils.getNowDate());
        return serverInfoMapper.updateServerInfo(serverInfo);
    }

    /**
     * 批量删除服务列表
     * 
     * @param serverIds 需要删除的服务列表主键
     * @return 结果
     */
    @Override
    public int deleteServerInfoByServerIds(Long[] serverIds)
    {
        return serverInfoMapper.deleteServerInfoByServerIds(serverIds);
    }

    /**
     * 删除服务列表信息
     * 
     * @param serverId 服务列表主键
     * @return 结果
     */
    @Override
    public int deleteServerInfoByServerId(Long serverId)
    {
        return serverInfoMapper.deleteServerInfoByServerId(serverId);
    }

    /**
     * @Description: 端口查询
     * @Author: xrw 
     * @Date: 2023/11/14 15:50
     * @Param: [serverInf]
     * @return: java.util.List<java.lang.Integer>
     **/
    @Override
    public List<Integer> getUsedPorts(ServerInfo serverInf)
    {
        return RemotePortScannerSSH.getUsedPorts(serverInf.getHostIp(),serverInf.getUserName(),serverInf.getPassword(),Integer.parseInt(serverInf.getSshPort()));
    }


    /**
     * @Description: 是否ping通 0不通 1通
     * @Author: xrw
     * @Date: 2023/11/9 20:55
     * @Param: [serverAddress]
     * @return: int
     **/
    private static int isServerHealthy(String serverAddress) {
        try {
            InetAddress address = InetAddress.getByName(serverAddress);
            if (address.isReachable(1000)){
                return 1;
            }; // 5000ms timeout
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
